#ifndef Writer_cxx
#define Writer_cxx

#include "Writer.h"

namespace FPTK{

template<class PixelType,unsigned int Dimension>
writer<PixelType,Dimension>::writer()
{
name=NULL;
filename=NULL;
extension=NULL;
add=NULL;
writer_so=NULL;
writer_image=NULL;
out=&(std::cout);
}

template<class PixelType,unsigned int Dimension>
writer<PixelType,Dimension>::~writer()
{
delete []name;
delete []filename;
delete []extension;
delete []add;
}

template<class PixelType,unsigned int Dimension>
int writer<PixelType,Dimension>::SetInputImage(ImageTypePointer image)
{
if(!image)
   {
   return -1;
   }
writer_image = WriterTypeImage::New();
writer_image->SetInput( image );
return 0;
}

template<class PixelType,unsigned int Dimension>
int writer<PixelType,Dimension>::SetInputSpatialObject(BlobTypePointer blob_image)
{
if(!blob_image)
   {
   return NULL;
   }
writer_so = WriterTypeSO::New();
writer_so->SetInput(blob_image);
return 0;
}
      
template<class PixelType,unsigned int Dimension>
char* writer<PixelType,Dimension>::GetName()
{
return name;
}


template<class PixelType,unsigned int Dimension>
int writer<PixelType,Dimension>::SetName(char* _filename,char *_add)
{
delete filename;
filename=new char[strlen(_filename)+1];
strcpy(filename,_filename);
delete add;
add=new char[strlen(_add)+1];
strcpy(add,_add);
return 0;
}

template<class PixelType,unsigned int Dimension>
int writer<PixelType,Dimension>::SetExtension(char *_extension)
{
delete extension;
extension=new char[strlen(_extension)+1];
strcpy(extension,_extension);
return 0;
}
      
template<class PixelType,unsigned int Dimension>
int writer<PixelType,Dimension>::Update()
{
if(CreateName())
   {
   return -1;
   }
if(!strcmp(extension,"meta"))
   {
   writer_so->SetFileName(name);
   writer_so->Update();
   }
else if(!strcmp(extension,"mha") || !strcmp(extension,"gipl"))
   {
   writer_image->SetFileName( name );   
   writer_image->Update();
   }
return 0;
}
      
      
template<class PixelType,unsigned int Dimension>
int writer<PixelType,Dimension>::CreateName()
{
if(filename==NULL || add==NULL || extension==NULL)
   {
   return -1;
   }
char *registr;
char *pointeur;
pointeur=filename;
pointeur=strrchr(filename,'.');
registr=new char[strlen(filename)+strlen(add)+1+strlen(extension)+1-(strlen(pointeur)-1)];
strcpy(registr,filename);
pointeur=strrchr(registr,'.');
if(strcmp(add,""))
   {
   strcpy(pointeur,"_");
   pointeur++;
   }
strcpy(pointeur,add);
strcat(registr,".");
strcat(registr,extension);
delete name;
name=new char[strlen(registr)+1];
strcpy(name,registr);
(*out)<<name<<std::endl;
delete []registr;
return 0;
}


}//end of FPTK namespace

#endif